package com.example.myapplication;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.example.myapplication.api.AuthInterceptor;
import com.example.myapplication.api.PasswordApi;
import com.example.myapplication.model.CreatePasswordRequest;
import com.example.myapplication.model.GeneratePasswordRequest;
import com.example.myapplication.model.Password;
import com.example.myapplication.model.PasswordStrength;

import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.textfield.TextInputEditText;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class PasswordDetailActivity extends AppCompatActivity {
    private PasswordApi passwordApi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_password_detail);

        // 设置Toolbar
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }

        // 初始化Retrofit
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new AuthInterceptor(this))
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://10.0.2.2:8080/")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        
        passwordApi = retrofit.create(PasswordApi.class);

        // 获取传递的密码数据
        Password password = (Password) getIntent().getSerializableExtra("password");
        if (password != null) {
            displayPasswordDetails(password);
            checkPasswordStrength(password.getPassword());
        }

        // 设置复制密码按钮点击事件
        ImageButton btnCopyPassword = findViewById(R.id.btnCopyPassword);
        btnCopyPassword.setOnClickListener(v -> {
            Password currentPassword = (Password) getIntent().getSerializableExtra("password");
            if (currentPassword != null) {
                ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clip = ClipData.newPlainText("密码", currentPassword.getPassword());
                clipboard.setPrimaryClip(clip);
                Toast.makeText(this, "密码已复制到剪贴板", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void displayPasswordDetails(Password password) {
        TextView tvTitle = findViewById(R.id.tvTitle);
        TextView tvWebsite = findViewById(R.id.tvWebsite);
        TextView tvUsername = findViewById(R.id.tvUsername);
        TextView tvPassword = findViewById(R.id.tvPassword);
        TextView tvNotes = findViewById(R.id.tvNotes);

        tvTitle.setText(password.getWebsite());
        tvWebsite.setText("网址：" + password.getWebsite());
        tvUsername.setText("用户名：" + password.getUsername());
        tvPassword.setText("密码：" + password.getPassword());
        tvNotes.setText("备注：" + password.getNote());
    }

    private void checkPasswordStrength(String password) {
        passwordApi.checkPasswordStrength(password).enqueue(new Callback<PasswordStrength>() {
            @Override
            public void onResponse(Call<PasswordStrength> call, Response<PasswordStrength> response) {
                if (response.isSuccessful() && response.body() != null) {
                    PasswordStrength strength = response.body();
                    updateStrengthUI(strength);
                } else {
                    Toast.makeText(PasswordDetailActivity.this, 
                        "获取密码强度失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<PasswordStrength> call, Throwable t) {
                Toast.makeText(PasswordDetailActivity.this, 
                    "网络错误", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void updateStrengthUI(PasswordStrength strength) {
        ProgressBar strengthProgress = findViewById(R.id.strengthProgress);
        TextView tvStrengthFeedback = findViewById(R.id.tvStrengthFeedback);

        strengthProgress.setProgress(strength.getScore());
        tvStrengthFeedback.setText(strength.getFeedback());
    }

    private void showEditDialog() {
        Password currentPassword = (Password) getIntent().getSerializableExtra("password");
        if (currentPassword == null) return;

        View dialogView = getLayoutInflater().inflate(R.layout.dialog_edit_password, null);
        TextInputEditText etTitle = dialogView.findViewById(R.id.etTitle);
        TextInputEditText etWebsite = dialogView.findViewById(R.id.etWebsite);
        TextInputEditText etUsername = dialogView.findViewById(R.id.etUsername);
        TextInputEditText etPassword = dialogView.findViewById(R.id.etPassword);
        TextInputEditText etNotes = dialogView.findViewById(R.id.etNotes);

        // 设置当前值
        etTitle.setText(currentPassword.getWebsite());
        etWebsite.setText(currentPassword.getWebsite());
        etUsername.setText(currentPassword.getUsername());
        etPassword.setText(currentPassword.getPassword());
        etNotes.setText(currentPassword.getNote());

        new MaterialAlertDialogBuilder(this)
            .setTitle("编辑密码")
            .setView(dialogView)
            .setPositiveButton("保存", (dialog, which) -> {
                CreatePasswordRequest request = new CreatePasswordRequest(
                    etTitle.getText().toString(),
                    etUsername.getText().toString(),
                    etPassword.getText().toString(),
                    etWebsite.getText().toString(),
                    etNotes.getText().toString()
                );
                updatePassword(currentPassword.getId(), request);
            })
            .setNegativeButton("取消", null)
            .show();
    }

    private void updatePassword(Long id, CreatePasswordRequest request) {
        passwordApi.updatePassword(id, request).enqueue(new Callback<Password>() {
            @Override
            public void onResponse(Call<Password> call, Response<Password> response) {
                if (response.isSuccessful() && response.body() != null) {
                    Toast.makeText(PasswordDetailActivity.this, 
                        "更新成功", Toast.LENGTH_SHORT).show();
                    // 刷新界面
                    displayPasswordDetails(response.body());
                    checkPasswordStrength(response.body().getPassword());
                    // 更新Intent中的密码数据
                    getIntent().putExtra("password", response.body());
                } else {
                    Toast.makeText(PasswordDetailActivity.this, 
                        "更新失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Password> call, Throwable t) {
                Toast.makeText(PasswordDetailActivity.this, 
                    "网络错误", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void showDeleteConfirmDialog() {
        Password currentPassword = (Password) getIntent().getSerializableExtra("password");
        if (currentPassword == null) return;

        new MaterialAlertDialogBuilder(this)
            .setTitle("删除密码")
            .setMessage("确定要删除这个密码吗？此操作不可恢复。")
            .setPositiveButton("删除", (dialog, which) -> 
                deletePassword(currentPassword.getId()))
            .setNegativeButton("取消", null)
            .show();
    }

    private void deletePassword(Long id) {
        passwordApi.deletePassword(id).enqueue(new Callback<Void>() {
            @Override
            public void onResponse(Call<Void> call, Response<Void> response) {
                if (response.isSuccessful()) {
                    Toast.makeText(PasswordDetailActivity.this, 
                        "删除成功", Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    Toast.makeText(PasswordDetailActivity.this, 
                        "删除失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Void> call, Throwable t) {
                Toast.makeText(PasswordDetailActivity.this, 
                    "网络错误", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            finish();
            return true;
        } else if (id == R.id.action_edit) {
            showEditDialog();
            return true;
        } else if (id == R.id.action_delete) {
            showDeleteConfirmDialog();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_password_detail, menu);
        return true;
    }
} 